﻿using SHDocVw;
using SUNRPA.CONTROLS.IMPL.domain;
using System.Runtime.InteropServices;

namespace SUNRPA.CONTROLS.IMPL.util {
    public class IEUtil : BrowserUtil{
        public override void ActiveBrowser() {
            throw new NotImplementedException();
        }

        public override void DealDownLoadDialog(bool isDownload, string parentPath, string fileName, int expireTime) {
            throw new NotImplementedException();
        }

        public InternetExplorer? GetLatestIeTab() { 
            SHDocVw.ShellWindows shellWins = new SHDocVw.ShellWindows();
            int tabCount = shellWins.Count - 1;
            while(tabCount >= 0) { 
                //as转换类型不对会为null
                InternetExplorer bro = shellWins.Item(tabCount) as InternetExplorer;
                if(bro != null && bro.Name.Equals("Internet Explorer")) { 
                    return bro;
                }
                tabCount--;
            }
            return null;
        }

        public override bool IsDownloadExpire(int downloadId, int expireTime) {
            throw new NotImplementedException();
        }

        public override object OpenUrl(string url, int expireTime, string? appPath) {
            using(AutoResetEvent ae = new AutoResetEvent(false)) { 
                //查看当前是否存在IE浏览器
                InternetExplorer browser = null;
                InternetExplorer existBro = GetLatestIeTab();
                if(existBro != null) { 
                    existBro.Navigate2(url, 0x1000);
                    browser = GetLatestIeTab();
                } else { 
                    browser = new InternetExplorer();
                    browser.Navigate2(url);
                }
                User32Utils.SetForegroundWindow(new IntPtr(browser.HWND));
                User32Utils.BringWindowToTop(new IntPtr(browser.HWND));
                browser.Navigate(url, true);
                browser.Visible = true;
                browser.DocumentComplete += delegate{ ae.Set(); }; 
                ae.WaitOne(expireTime * 1000);
                return browser;
            }
        }

        public override object SearchLatestDownloadTask() {
            throw new NotImplementedException();
        }

        public override bool WaitWebEle(int waitType, bool canExpire, WebElement ele, object webPage, [Optional] int expireTime) {
            throw new NotImplementedException();
        }
    }
}
